#pragma once
#include "nocopy.hpp"
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <cstdlib>
#include <string>
#include <strings.h>
#include "Log.hpp"
#include "Comm.hpp"

// const std::string defaultip = "0.0.0.0";
const uint16_t defaultport = 8888;
const int default_size = 1024;

class UdpService : public nocopy
{
public:
    // UdpService(const std::string &ip = defaultip, uint16_t port = defaultport)
    //     : _ip(ip), _port(port)
    // {
    // }

    UdpService(uint16_t port = defaultport)
        : _port(port)
    {
    }

    void Init()
    {
        // 创建socket，创建网卡文件细节
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            lg.LogMessage(Fatal, "socket err, %d, %s\n", errno, strerror(errno));
            exit(Socket_err);
        }

        // 绑定网络信息
        struct sockaddr_in local;
        bzero(&local, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        // local.sin_addr.s_addr = inet_addr(_ip.c_str()); // 字符串转4字节整数， 主机序列转网络序列
        local.sin_addr.s_addr = INADDR_ANY;

        int m = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (m != 0)
        {
            lg.LogMessage(Fatal, "socket bind err, %d:%s\n", errno, strerror(errno));
            exit(Bind_err);
        }
    }

    void Start()
    {
        char buffer[default_size];
        while (true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << "client say# " << buffer << std::endl;
                sendto(_sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&peer, len);
            }
        }
    }

    ~UdpService()
    {
    }

    // private:
    uint16_t _port;
    // std::string _ip;
    int _sockfd;
};